<?PHP

require_once ("config.php");

$db = new SQLite3(CONF_SENSOR_DB_SQLITE);

if (isset($_GET["new"])) {
	$id = (int) $_GET["new"];
	if (@$db->exec('INSERT OR REPLACE INTO sensors (id,x,y) VALUES ('.$id.',0,0)')) {
		header("Location: ./map.php");
		die();
	} else {
		die('Failed to update DB');
	}
}

if (isset($_GET["del"])) {
	$id = (int) $_GET["del"];
	if (@$db->exec('DELETE FROM sensors WHERE id = '.$id)) {
		header("Location: ./map.php");
		die();
	} else {
		die('Failed to update DB');
	}
}


$results = $db->query('SELECT id, x, y FROM sensors');


?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CoolSens map</title>
<link type="text/css" href="../css/ui-lightness/jquery-ui-1.8.13.custom.css" rel="Stylesheet" />	
<script type="text/javascript" src="../js/jquery-1.6.1.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.8.13.custom.min.js"></script>

<body style="margin: 0; padding: 0;font:0.75em/1.7em Verdana,Arial,Geneva,Helvetica,sans-serif;">


<style>
	.sensor { cursor: pointer; position: absolute; text-align:center; width: 30px; height: 40px; padding: 0.5em; border: 2px solid #337CAE; -moz-border-radius: 5px; border-radius: 5px; padding: 2px; font-size: 9px;}

	.sensor .temp {text-align: center;font-weight: bold; font-size: 11px; line-height:12px;}
	.sensor .led, #status {position: relative; margin-bottom: 5px;}
	.sensor .led img, #status img {width: 10px; height: 10px;position: absolute; top: 0; left: 10px;}
	.sensor .alltemp {display: none; position: absolute; top: 45px; left: -70px;width: 180px; height: 150px; overflow-y:auto; overflow-x: hidden;}
	.sensor .alltemp table {width: 100%; font: 10px Verdana,Arial,Geneva,Helvetica,sans-serif}
	.sensor .alltemp th {font-style: italic; }
	.sensor .alltemp .warning {color: red; }
</style>
<div class="map" style="position relative; width: 960px; height: 600px; border: 1px solid #666666;">
<div style="bottom: 0; left: 0px; position: absolute; color: #666666;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Connection to server<div id="status" class="led" style="position: absolute; top: 5px; left: 0px;"><img class="red" src="../Images/led_red.png" /><img class="green" src="../Images/led_green.png" style="display: none;" /></div></div>

<img style="width: 100%; height: 100%;" src="../Images/map.jpg" />
<?
while ($row = $results->fetchArray()) {
	?>

	<script>
		$(function() {
			var id = <? print $row["id"]; ?>; 
			$( "#sensor"+id ).draggable({ containment: 'parent', stop: function(event, ui) {save(id, $(this).position().left, $(this).position().top); return true;}, cancel: ".alltemp" });
			$( "#sensor"+id ).dblclick(function() {$(this).children(".alltemp").toggle(500);});
		});
	</script>
	<div id="sensor<? print $row["id"]; ?>" class="sensor  ui-widget-content" style="left: <? print $row["x"]; ?>px; top: <? print $row["y"]; ?>px;">
		<div class="led"><img class="red" src="../Images/led_red.png" /><img class="green" src="../Images/led_green.png" style="display: none;" /></div>
		#<? print $row["id"]; ?>
		<div class="temp">?&ordm;</div>
		<div class="ui-widget-content alltemp">
		<a href="map.php?del=<? print $row["id"]; ?>">Remove node</a>
		<table>
			<tr><th>Time received</th><th style="width: 40px;">Packet</th><th style="width: 35px;">Temp.</th></tr>
		</table>
		</div>
	</div>
	<?
}
?>


</div>

<script>
	function save(id, x, y) {
		$.get("update.php", { action: "sensor", id: id, x: x, y: y },
		function(data){
			if (data != "ok") alert("Error occured while saving position: " + data);
		}, "json");
   	}
   	
	function blink (el) {
		el.toggle();
		clearTimeout(el._timeout);
		el._timeout = setTimeout(function(){blink(el);}, 1000);
	}
   	
   	function pool(last) {
	   	setTimeout(function() {
			$.ajax({
			  url: "update.php",
			  data: { action: "pool", last: last},
			  success: function(data){
					if (data.data) {
						$.each(data.data, function(index, value) {
							if ($("#sensor"+value.id)) {
								$("#sensor"+value.id+" .alltemp table").append("<tr><td>"+value.time_str+"</td><td"+($("#sensor"+value.id).prop("_lastvalue") != undefined && $("#sensor"+value.id).prop("_lastvalue")+1 != value.num? " class='warning'":"")+">#"+value.num+"</td><td>"+(value.temp/10)+"&ordm;</td></tr>");
								$("#sensor"+value.id).prop("_lastvalue", value.num);
								$("#sensor"+value.id+" .temp")[0].innerHTML = (value.temp/10)+"&ordm;";
								// red sequence
								var red = $( "#sensor"+value.id+" .red" );
								clearInterval(red.prop('_blinkinterval'));
								red.show();
								// green sequence
								var green = $( "#sensor"+value.id+" .green" );
								clearTimeout(green.prop('_timeout'));
								green.stop(true);
								green.show();
								green.css("opacity", 1);
								green.prop('_timeout', setTimeout(
									function(){
										green.fadeOut(<? print CONF_FADE_DELAY; ?>, function(){
										red.prop('_blinkinterval', setInterval(
											function(){
												red.toggle();
											},500));
										});
									}, 
									<? print CONF_OK_DELAY; ?>));
								
							}
							if (value.time > last) last = value.time;
						});
					}
					pool(last);
					// status leds
					// red sequence
					var red = $( "#status .red" );
					clearInterval(red.prop('_blinkinterval'));
					red.show();
					// green sequence
					var green = $( "#status .green" );
					clearTimeout(green.prop('_timeout'));
					green.stop(true);
					green.show(0);
					green.prop('_timeout', setTimeout(
						function(){
							green.hide(0);
							red.prop('_blinkinterval', setInterval(
								function(){
									red.toggle();
								},500));
						}, 4000));
						
				},
			  error : function(){	
					pool(last);
				},
			  dataType: "json"
			});
		}, 2000);
	}
	pool(0);

</script>
	
	
</body></html>
